﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TurtleLib.ComputerCraft
{
  /// <summary>
  /// A string class that hold metadata about the text - it may represent multiple segments of differing metadata
  /// </summary>
  public class TermString
  {
    private TermSegment[] _data;

    public int Length { get { return _data.Length; } }
    public TermSegment this[int i] { get { return _data[i]; } set { _data[i] = value; } }

    public class TermSegment
    {
      public colors BackgroundColor { get; set; }
      public colors ForeColor { get; set; }
      public string Text { get; set; }

      internal TermSegment()
      {
        Text = " ";
        BackgroundColor = colors.black;
        ForeColor = colors.white;
      }

      public override string ToString()
      {
        return string.Format("{0} {1}/{2}", Text, ForeColor, BackgroundColor);
      }
    }

    internal TermString(int length)
    {
      _data = new TermSegment[length];

      for (int i = 0; i < length; i++)
      {
        _data[i] = new TermSegment { BackgroundColor = 0, ForeColor = 0, Text = " " };
      }
    }

    internal TermString(colors background, colors foreground, string text, int length)
    {
      _data = new TermSegment[length];

      for (int i = 0; i < text.Length && i < _data.Length; i++)
      {
        var tc = new TermSegment();
        tc.BackgroundColor = background;
        tc.ForeColor = foreground;
        tc.Text = text[i].ToString();

        _data[i] = tc;
      }
    }

    public TermString Replace(TermString ts, int offset)
    {
      for (int i = offset; i < _data.Length && (i - offset) < ts.Length; i++)
      {
        if (i < 0)
          continue;

        _data[i] = ts[i - offset];
      }

      return this;
    }

    public IEnumerable<TermSegment> GetSegments()
    {
      TermSegment current = null;

      for (int i = 0; i <= _data.Length; i++)
      {
        var seg = i < _data.Length ? _data[i] : null;

        if (current == null)
          current = new TermSegment { BackgroundColor = seg.BackgroundColor, ForeColor = seg.ForeColor, Text = seg.Text };
        else if (seg != null && current.BackgroundColor == seg.BackgroundColor && current.ForeColor == seg.ForeColor)
          current.Text += seg.Text;
        else
        {
          yield return current;

          if (seg == null)
            break;

          current = null;
          i--;
        }
      }
    }

    public override string ToString()
    {
      return string.Join("", _data.Where(d => d != null).Select(d => d.Text));
    }
  }
}
